package com.bookpavilion.chat.service;

import com.alibaba.fastjson.JSON;
import com.bookpavilion.chat.dao.MessageDao;
import com.bookpavilion.chat.netty.ChatHandler;
import com.bookpavilion.chat.pojo.Message;
import com.bookpavilion.chat.pojo.SystemMessage;
import com.bookpavilion.chat.pojo.User;
import com.mongodb.MongoClient;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.MongoCollection;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RabbitListener(queues = "sys_msg")
public class MessageService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询对话最新信息
     * @param fromId
     * @param toId
     * @return
     */
    public Message queryLastMessage(String fromId,String toId){
        Query query = new Query();
        query.addCriteria(Criteria.where("from.id").is(fromId).and("toId").is(toId)).with(Sort.by(Sort.Order.desc("send_date")));
        Message message = mongoTemplate.findOne(query, Message.class);
        return message;

    }

    /**
     *查询所有信息
     * @return
     */
    public List<Message> findAll(){
        return messageDao.findAll();
    }

    /**
     *  根据消息Id更改信息状态 status :  0 未读  1 已读  -1 无效
     * @param id
     * @param status
     */
    public void updateMessStatusById(String id, Integer status){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("status",status);
        mongoTemplate.updateFirst(query,update,"message");

    }

    public void updateMessListById(List<String> ids,Integer status){
        BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED,"message");
        ids.forEach(date->{
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(date));
            Update update = new Update();
            update.set("status",status);
            update.set("readDate",new Date());
            operations.updateOne(query,update);
        });
        BulkWriteResult execute = operations.execute();
    }

    /**
     * 查询对话所有有效信息 分页形式
     * @param fromId
     * @param toId
     * @param page
     * @param size
     * @return
     */
    public List<Message> queryMessageList(String fromId, String toId, Integer page, Integer size) {
        Pageable pageable =PageRequest.of(page-1,size);
        Query query = new Query();
        query.addCriteria(Criteria.where("from.id").is(fromId).and("to.id").is(toId).and("status").ne(-1)).with(pageable);
        List<Message> messages = mongoTemplate.find(query, Message.class);
        return messages;
    }

    /**
     * 删除对话所有聊天记录    （修改信息 status : -1 ）
     * @param fromId
     * @param toId
     */
    public void deleteMessageList(String fromId, String toId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("from._id").is(fromId).and("to._id").is(toId));
        Update update = new Update();
        update.set("status",-1);
        mongoTemplate.updateMulti(query,update,"message");
    }

    public List<Message> getUnReadMsgList(String acceptUserId) {
        Query query = new Query();
        query.addCriteria(new Criteria("to._id").is(acceptUserId).and("status").is(0));
        List<Message> messages = mongoTemplate.find(query, Message.class);
        return messages;
    }

    public void sendSystemMsg(SystemMessage systemMessage) {
        MongoClient client = new MongoClient("192.168.255.134");
        MongoCollection<Document> collection = client.getDatabase("message").getCollection("system_message");
        Document document = new Document();
        String sys_msg = JSON.toJSONString(systemMessage);
        document.put("sys_msg",sys_msg);
        collection.insertOne(document);
        rabbitTemplate.convertAndSend("sys_msg",sys_msg);
    }
    @RabbitHandler
    public void onMessage(String text){
        ChatHandler chatHandler = new ChatHandler();
        ChannelGroup usersChannel = chatHandler.getUsersChannel();
        usersChannel.writeAndFlush(new TextWebSocketFrame(text));
    }
}
